import { Cell, Graph } from "@antv/x6";
import { updateNodes } from "@/utils/antvx6/nodeAndEdgeUpdate";
import useDrawingBoard from "@/store/modules/drawingBoard";

/**
 * 监听滚轮编辑节点角度
 * @param { HTMLElement }  graph  antv x6 元素
 */
export const changeNodePointAngle = (graph: Graph) => {
  const drawingBoardStore = useDrawingBoard();
  // 节点getData缓存
  let _row: any = {};
  let isKeyDownA: boolean = false; // 是否按下组合按键
  let nodeSelected: Cell | any = null;
  const cansBoard: HTMLElement = document.querySelector("#container") as HTMLElement;

  graph.bindKey(
    "R",
    (e: any) => {
      isKeyDownA = false;
      if (drawingBoardStore.nodeSelectedList.length === 1) {
        isKeyDownA = true;
        nodeSelected = drawingBoardStore.nodeSelectedList[0];
        _row = nodeSelected?.getData();
        if (_row?.hasDirection) {
          cansBoard.addEventListener("wheel", changeAngle);
        }
      }
    },
    "keydown"
  );

  graph.bindKey(
    "R",
    (e: any) => {
      if (_row?.hasDirection) {
        cansBoard.removeEventListener("wheel", changeAngle);
        updateNodes(_row);
      }
    },
    "keyup"
  );

  function changeAngle(event: WheelEvent | any) {
    if (!isKeyDownA) return;
    // 角度值取值范围  -180 ~ 180
    if (event.wheelDelta > 0) {
      // 上滚
      _row.angle -= 1;
      _row.angle < -180 && (_row.angle = 360 + _row.angle);
    } else {
      // 下滚
      _row.angle += 1;
      _row.angle > 180 && (_row.angle = (360 - _row.angle) * -1);
    }
    nodeSelected.prop("angleDirection", _row.angle);
  }
};
